﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD.LopPlat.UI
{
    public partial class Create_RSA : Form
    {
        public Create_RSA()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            // 获取私钥和公钥。
            string privateKey = rsa.ToXmlString(true);
            string publicKey = rsa.ToXmlString(false);

            this.txtPrivateKey.Text = privateKey;
            this.txtPublicKey.Text = publicKey;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "请选择保存路径！";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                string path = folder.SelectedPath;
                this.textBox1.Text = path;
            }
        }

        private void Create_RSA_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.textBox1.Text.Trim().Length == 0)
                {
                    throw new Exception("请选择保存的位置！");
                }
                else
                {
                    string path = this.textBox1.Text.Trim();

                    DateTime now = DateTime.Now;
                    string fileName = now.ToString("yyyyMMddHHmmss");

                    string privateKey = this.txtPrivateKey.Text.Trim();
                    string publicKey = this.txtPublicKey.Text.Trim();

                    if (privateKey.Length == 0 || publicKey.Length == 0)
                    {
                        throw new Exception("请选生成私钥和公钥！");
                    }
                    File.WriteAllText(Path.Combine(path, fileName + ".pvk"), privateKey);
                    File.WriteAllText(Path.Combine(path, fileName + ".spc"), publicKey);

                    Tools.PromptHelper.Prompt("导出成功！");
                }
            }
            catch (Exception ex)
            {
                Tools.PromptHelper.Prompt(ex);
            }
        }
    }
}
